package cn.lzj.pet.service.impl;

import cn.lzj.basic.exception.BusinessException;
import cn.lzj.basic.service.IBaiduAiAuditService;
import cn.lzj.basic.service.impl.BaseServiceImpl;
import cn.lzj.basic.util.*;
import cn.lzj.order.domain.OrderPetAcquisition;
import cn.lzj.order.mapper.OrderPetAcquisitionMapper;
import cn.lzj.org.domain.Employee;
import cn.lzj.org.domain.Shop;
import cn.lzj.org.mapper.EmployeeMapper;
import cn.lzj.org.mapper.ShopMapper;
import cn.lzj.pet.domain.Pet;
import cn.lzj.pet.domain.SearchMasterMsg;
import cn.lzj.pet.domain.SearchMasterMsgAuditLog;
import cn.lzj.pet.dto.MsgDto;
import cn.lzj.pet.mapper.PetMapper;
import cn.lzj.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.lzj.pet.mapper.SearchMasterMsgMapper;
import cn.lzj.pet.query.SearchMasterMsgQuery;
import cn.lzj.pet.service.ISearchMasterMsgService;
import cn.lzj.user.domain.Logininfo;
import cn.lzj.user.domain.User;
import cn.lzj.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;

/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private PetMapper petMapper;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;

    @Override
    public void publish(SearchMasterMsg searchMasterMsg, HttpServletRequest request) {
        Logininfo logininfo = LoginContext.getLoginUser(request);
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        //1.添加寻主消息
        searchMasterMsg.setUserId(user.getId());
        searchMasterMsgMapper.save(searchMasterMsg);
        //2.百度AI审核
        Boolean textBoo = BaiduAuditUtils.TextCensor(searchMasterMsg.getTitle());
        Boolean imageBoo = baiduAiAuditService.imageAudit(searchMasterMsg.getResources());
        if (textBoo && imageBoo) {
            //审核成功过后，对数据的操作
            //3.设置状态和日志
            searchMasterMsg.setState(1);
            searchMasterMsg.setNote("审核成功");
            //4.绑定店铺
            Point point = DistanceUtil.getPoint(searchMasterMsg.getAddress());
            Shop nearestShop = DistanceUtil.getNearestShop(point, shopMapper.loadAll());
            if (nearestShop != null) {
                searchMasterMsg.setShopId(nearestShop.getId());
                System.out.println("你有新的订单，请尽快处理：" + searchMasterMsg.getTitle());
            }
            searchMasterMsgMapper.update(searchMasterMsg);
            //添加审核日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(searchMasterMsg.getId());
            log.setState(1);//通过
            log.setNote("审核成功");
            searchMasterMsgAuditLogMapper.save(log);
        } else {
            searchMasterMsg.setState(0);
            searchMasterMsg.setNote("审核失败，内容非法");
            searchMasterMsgMapper.update(searchMasterMsg);

            //2.2.审核失败：修改寻主消息状态0 + 添加审核日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(searchMasterMsg.getId());
            //audit_id - 自动审核，没有添加审核人
            log.setState(0);//驳回
            log.setNote("审核失败，内容非法");
            searchMasterMsgAuditLogMapper.save(log);
            throw new BusinessException("审核失败，内容非法");
        }
    }

    @Override
    public PageList<SearchMasterMsg> user(SearchMasterMsgQuery query, HttpServletRequest request) {

        Logininfo logininfo = LoginContext.getLoginUser(request);
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        query.setUserId(user.getId());
        return super.queryPage(query);
    }

    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, HttpServletRequest request) {
        Logininfo logininfo = LoginContext.getLoginUser(request);
        Employee employee = employeeMapper.loadByLogininfoid(logininfo.getId());
        if (employee.getShop_id() != null) {
            query.setShopId(employee.getShop_id());
        }
        return super.queryPage(query);
    }

    @Override
    public void reject(Long msgId) {
        searchMasterMsgMapper.reject(msgId);
    }

    @Override
    public void accept(MsgDto msgDto) {
        Long empId = msgDto.getHandlerId();
        Long msgId = msgDto.getMsgId();
        String note = msgDto.getNote();
       OrderPetAcquisition orderTem= orderPetAcquisitionMapper.loadByMsgId(msgId);
       if(orderTem!=null){
           throw new BusinessException("订单正在处理");
       }
       //1.创建宠物对象
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.loadById(msgId);
        Pet pet = searchMasterMsg2pet(searchMasterMsg);
        petMapper.save(pet);

        //2.创建收购订单
        OrderPetAcquisition orderPetAcquisition = builderOrder(pet, searchMasterMsg, empId);
        //3.发短信或告诉收件人在规定时间之内处理
        orderPetAcquisitionMapper.save(orderPetAcquisition);
        System.out.println("你有新的订单，请在规定时间内处理完成！！");
    }

    private OrderPetAcquisition builderOrder(Pet pet, SearchMasterMsg msg, Long empId) {
        OrderPetAcquisition order = new OrderPetAcquisition();
        //System.out.println(order);//OrderPetAcquisition{, orderSn=null, digest=null, lastcomfirmtime=null, state=null, price=null, paytype=null, petId=null, userId=null, shopId=null, address=null, empId=null, searchMasterMsgId=null}
        System.out.println(pet.getUserId());
        String orderSn = CodeGenerateUtils.generateOrderSn(pet.getUserId());
        order.setOrderSn(orderSn);
        order.setDigest(msg.getTitle());
        Long timeTem=System.currentTimeMillis()+2*26*60*60*1000;
        order.setLastcomfirmtime(new Date(timeTem));
        order.setState(0);//待处理
        order.setPrice(new BigDecimal(msg.getPrice()));
        order.setPetId(pet.getId());
        order.setUserId(pet.getUserId());
        order.setShopId(pet.getShopId());
        order.setAddress(msg.getAddress());
        order.setEmpId(empId);
        order.setSearchMasterMsgId(msg.getId());
        return order;
    }

    private Pet searchMasterMsg2pet(SearchMasterMsg searchMasterMsg) {

        Pet pet = new Pet();
        pet.setName(searchMasterMsg.getName());
        pet.setCostprice(searchMasterMsg.getPrice().toString());
        pet.setTypeId(searchMasterMsg.getPetType());
        pet.setShopId(searchMasterMsg.getShopId());
        pet.setUserId(searchMasterMsg.getUserId());
        pet.setSearchMasterMsgId(searchMasterMsg.getId());
        pet.setResources(searchMasterMsg.getResources());
        return pet;
    }
}
